<?php
class cfg
{
    /**
     * The configuration of the website
     *
     * @var array $config
     */
	private $config = array();
	
	function __construct()
	{
		if(!file_exists("cfg/cfg.php"))
		{
			global $db;
			
			$file_cfg = fopen("cfg/cfg.php", 'x+');
			fwrite($file_cfg, "<?php\n");
			
			$sql = "SELECT * FROM config";
			$risultato = $db->query($sql);;
			while($row = mysql_fetch_assoc($risultato))
			{
				if(is_numeric($row['valore']))
				{
					fwrite($file_cfg, '$this->config[\''.$row['nome'].'\'] = '.$row['valore'].';' . "\n");
				}
				else 
				{
					fwrite($file_cfg, '$this->config[\''.$row['nome'].'\'] = "'.str_replace("\"", '\"', $row['valore']).'";' . "\n");
				}
				$this->config[$row['nome']] = $row['valore'];
			}
			
			fwrite($file_cfg, "?>");
			fclose($file_cfg);
		}
		else
		{
			include("cfg/cfg.php");
		}
	}
	
	public function get($key)
	{
		if ( isset($this->config[$key]) )
		{
			return $this->config[$key];
		}
		else
		{
			return false;
		}
	}

	public function set($key, $value)
	{
		global $db;
		
		if($value == $this->config[$key])
		{
			return;
		}
		
		$sql = "UPDATE config SET valore = '".input($value)."' WHERE nome = '".$key."' LIMIT 1";
		$db->query($sql);
				  
		if(file_exists("cfg/cfg.php"))
		{
			unlink("cfg/cfg.php");
		}
	}

     public function tmpset($key,$value){ $this->config[$key] = $value; }
}

$cfg = new cfg();
?>